package com.jiuyou.websocket.handler.base;

import com.jiuyou.websocket.manager.WebSocketSessionManager;
import com.jiuyou.websocket.service.LoginWebSocketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * WebSocket 对话服务处理器
 */

@Service
public class TalkWebSocketHandler extends AbstractWebSocketHandler {

    private final Logger log = LoggerFactory.getLogger(TalkWebSocketHandler.class);

    @Autowired
    private WebSocketSessionManager wsSessionManager;

    @Autowired
    private LoginWebSocketService loginWebSocketService;

    /**
     * 建立连接
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String sessionId = session.getId();
        //保存当前客户端session
        wsSessionManager.addClientMap(session.getId(), session);
        //增加客户端在线数量
        wsSessionManager.addOnlineCount();

        log.info("建立连接，sessionId：{}", sessionId);
        log.info("客户端数量：{}", wsSessionManager.getOnlineCount());

        loginWebSocketService.updateUserInfo(session);
    }

    /**
     * 连接关闭
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        String sessionId = session.getId();
        if (wsSessionManager.containsClientMap(sessionId)) {
            //连接关闭，移除当前客户端
            wsSessionManager.removeClient(session);
            //减去客户端在线数量
            wsSessionManager.subOnlineCount();

            log.info("离开，sessionId：{}", session.getId());
            log.info("客户端数量：{}", wsSessionManager.getOnlineCount());
        }
    }

    /**
     * 发生错误
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        exception.printStackTrace();
    }

    /**
     * 处理消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        // 获取接收到的数据
        /*String payload = message.getPayload();
        log.info("接收到消息：{}", payload);*/
    }

}
